import requests
from flask import request
import json
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

class MonitorAPIResource(BaseResource):
    # def get(self):
    #     result = models.Templates.get_id()
    #     return result[0]

    def post(self):
        req = request.get_json(force=True)
        deviceurl = req["deviceurl"]
        skillId = req["skillId"]
        deviceToken =req["deviceToken"]
        try:
            #停止渲染
            data = {
                "deviceToken": deviceToken
            }
            json_str = json.dumps(data)
            headers = {'content-type': 'application/json'}
            response = requests.post(
                "http://"+deviceurl+"/stop",
                data=json_str,
                timeout=3.0,
                headers=headers,
            )
            #开始渲染
            data = {
                "deviceToken": deviceToken,
                "skillId": skillId
            }
            json_str = json.dumps(data)
            headers = {'content-type': 'application/json'}
            response = requests.post(
                "http://"+deviceurl+"/start",
                data=json_str,
                timeout=3.0,
                headers=headers,
            )
            latest_version = response
            return latest_version.text

        except requests.RequestException:
            logging.exception("Failed checking for new version.")
        except (ValueError, KeyError):
            logging.exception(
                "Failed checking for new version (probably bad/non-JSON response)."
            )